//
//  CreateQuanziView.m
//  YiqiMobile
//
//  Created by henry on 13-4-30.
//  Copyright (c) 2013年 henry. All rights reserved.
//
#define  RELPAYVIEWTAG  1100
#define  YAOQINGBUTTONLabelTAG  1101
#define TABLEVIEWCELLHEIGHT 35
#import "RelypinglunView.h"
#import "QuartzCore/QuartzCore.h"
#import "Config.h"
#import "Utility.h"
#include "DefineAction.h"
#import "AppDelegate.h"
#import "JSON.h"
#import "HomePageViewController.h"


@interface RelypinglunView(private)
-(void) selectQuanziAction:(UIButton*) sender;
-(void) initTableView;
@end

@implementation RelypinglunView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
         self.backgroundColor=[UIColor colorWithRed:159.0/255 green:159.0/255 blue:159.0/255 alpha:0.2];
        UIView *replyView=[[UIView alloc] initWithFrame:CGRectMake(20, 100, 280, 150)];
        replyView.layer.cornerRadius=10;
        replyView.layer.masksToBounds=YES;
        replyView.tag=RELPAYVIEWTAG;
        replyView.backgroundColor=[UIColor whiteColor];
        [self addSubview:replyView];
        
       
        
        [replyView addSubview:[Utility customButton:self action:@selector(dissViewAction:) normalImage:@"quanzi_cannel_normal.png" lightedImage:@"quanzi_cannel_hover.png" frame:CGRectMake(12, 93, 124, 31) title:nil tag:66]];
        [replyView addSubview:[Utility customButton:self action:@selector(saveAction:) normalImage:@"replayButton_normal.png" lightedImage:@"replayButton_hover.png" frame:CGRectMake(144, 93, 124, 31) title:nil tag:67]];

        // Initialization code
    }
    return self;
}
-(void) showInputField:(int) type{
    self.type=type;
    UIView *replyView=[self viewWithTag:RELPAYVIEWTAG];
    if (type==1) {
        UILabel *quanziLabel=[Utility detailTextLabel:CGRectMake(12, 13, 100, 13) andFontSize:12];
        quanziLabel.text=@"输入回复内容";
        [replyView addSubview:quanziLabel];
        
        UIImageView *inputBg=[[UIImageView alloc] initWithFrame:CGRectMake(11.5, 36, 257, 54)];
        inputBg.image=[Utility imageNamed:@"createQuanzi_inputbg.png"];
        [replyView addSubview:inputBg];
        
        
        self.textView=[[UITextView alloc] initWithFrame:CGRectMake(11.5, 36, 257, 54)];
        self.textView.backgroundColor=[UIColor  clearColor];
        self.textView.layer.cornerRadius = 8;//设置那个圆角的有多圆
        self.textView.layer.borderWidth = 0;//设置边框的宽度，当然可以不要
        //self.textView.layer.borderColor = [[UIColor blackColor] CGColor];//设置边框的颜色
        self.textView.keyboardType=UIKeyboardTypeDefault;
        self.textView.layer.masksToBounds = YES;//设为NO去试试
        self.textView.autocorrectionType=UITextAutocorrectionTypeNo;
        self.textView.returnKeyType=UIReturnKeySend;
        self.textView.textColor=[UIColor blackColor];
        self.textView.font=[UIFont fontWithName:FONT_FAMILY size:15.0];
        self.textView.enablesReturnKeyAutomatically=YES;
        [self.textView becomeFirstResponder];
        self.textView.delegate=self;
        [replyView addSubview:self.textView];
    }else{//邀请他
        [self initTableView];
        UIButton *selectqzbutton=[Utility customButton:self action:@selector(selectQuanziAction:) normalImage:@"replayselectqzbutton.png" lightedImage:@"replayselectqzbutton.png" frame:CGRectMake(11.5, 17, 254.5, 32) title:nil tag:0];
        [replyView addSubview:selectqzbutton];
        
        UILabel *quanziLabel=[Utility detailTextLabel:CGRectMake(11.5, 6, 200, 20) andFontSize:15];
        quanziLabel.tag=YAOQINGBUTTONLabelTAG;
        quanziLabel.textColor=[UIColor  blackColor];
        quanziLabel.text=@"请选择所在圈子";
        [selectqzbutton addSubview:quanziLabel];
        
        UIImageView *inputBg=[[UIImageView alloc] initWithFrame:CGRectMake(11.5, 56, 257, 34)];
        inputBg.image=[Utility imageNamed:@"createQuanzi_inputbg.png"];
        [replyView addSubview:inputBg];
        self.textField = [self customTextField:CGRectMake(11.5, 56, 257, 34)];
        self.textField.delegate=self;
        [replyView
         addSubview:self.textField];
    }
}

//加载圈子
-(void) initTableView{
    
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    CustomTabBarController *nav=[app.tabBarController.viewControllers objectAtIndex:0];
    HomePageViewController *homePageViewController=[nav.viewControllers   objectAtIndex:0];
    NSArray *option=homePageViewController.pushMenuView.options;
    self.quanliList=[NSMutableArray array];
    if ([option count]>0) {
        [self.quanliList addObjectsFromArray:[[option objectAtIndex:0] objectForKey:@"list"]];
    }
    
    [self.textField resignFirstResponder];
    float height=210;
    /*if ([self.quanliList count]>6) {
        height=210;
    }*/
     UIView *replyView=[self viewWithTag:RELPAYVIEWTAG];
    CGRect tableViewFrame=CGRectMake(replyView.frame.origin.x+5, replyView.frame.origin.y+49-8, 270, height);
    self.mytableView=[[UITableView alloc] initWithFrame:tableViewFrame style:UITableViewStyleGrouped];
    self.mytableView.backgroundView=nil;
    self.mytableView.bounces=NO;
    self.mytableView.backgroundColor=[UIColor clearColor];
    self.mytableView.tag=HOMEPAGETABLEVIEWTAG;
    self.mytableView.showsVerticalScrollIndicator=NO;
    self.mytableView.separatorStyle=UITableViewCellEditingStyleNone;
    self.mytableView.delegate=self;
    self.mytableView.dataSource=self;
    self.mytableView.hidden=YES;
    [self addSubview:self.mytableView];
    
    

}

-(void) selectQuanziAction:(UIButton*) sender{
    self.mytableView.hidden=!self.mytableView.hidden;
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if (1 == range.length) {//按下回格键
        return YES;
    }
    if ([text isEqualToString:@"\n"]) {//按下return键
        [self saveAction:nil];
        //这里隐藏键盘，不做任何处理
        //[textView resignFirstResponder];
        
        return NO;
    }else {
        if ([textView.text length] < 140) {//判断字符个数
            return YES;
        }
    }
    return NO;
}

#pragma -mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==self.textField) {
        if (self.textField.text.length>0) {
            [self.textField resignFirstResponder];
            [self saveAction:nil];
            return YES;
        }
    }
    return NO;
} 

-(void) dissViewAction:(UIButton*) sender{
   [self removeFromSuperview];  
}


-(void) saveAction:(UIButton*) sender{
  
    //保存数据
    AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
    if (app.status==NotReachable) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        return;
    }
    
    if (self.type==1) {//评论回复
        NSString *content=self.textView.text;
        if (content==nil||[content isEqualToString:@""]) {
            [Utility customAlertWithMsg:@"请输入回复内容" andTitle:ALRRTTITLE andDelagate:nil];
            return;
        }
        NSString *userId=[[NSUserDefaults standardUserDefaults] objectForKey:USERID];
        NSMutableDictionary *param=[NSMutableDictionary dictionary];
        [param setObject:userId forKey:@"ph.u0"];//发起人
        [param setObject:@"" forKey:@"ph.ph2"];//接受人
        [param setObject:content forKey:@"ph.ph3"];//内容
        [param setObject:@"1" forKey:@"ph.t0"];//类型
        [param setObject:self.pinglunId forKey:@"ph.ph5"];//评论ID
        NSString *url=[NSString stringWithFormat:@"%@/%@",[Utility  getServerUrl],ADDPINGLUNREPLY];
        self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:param andFile:nil];
        [self.request startLoadData];
    }else{
        if (self.selectQuanziId==nil) {
            [Utility customAlertWithMsg:@"请选择圈子" andTitle:ALRRTTITLE andDelagate:nil];
            return;
        }
        
        NSString *content=self.textField.text;
        if (content==nil||[content isEqualToString:@""]) {
            [Utility customAlertWithMsg:@"请输入消息" andTitle:ALRRTTITLE andDelagate:nil];
            return;
        }
        
       [Utility customAlertWithMsg:@"亲，API还没提供接口" andTitle:ALRRTTITLE andDelagate:nil];
    }
  
    

}
- (void)requestFinished:(id)context{
    @try{
        NSDictionary *result=[context JSONValue];
        if ([[result  objectForKey:@"method"] isEqualToString:ADDPINGLUNREPLY]) {//发表供稿评论回复
            AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication] delegate];
            CustomTabBarController *nav=[app.tabBarController.viewControllers objectAtIndex:1];
            UIViewController *viewController=[nav.viewControllers   lastObject];
            if ([viewController respondsToSelector:@selector(loadPinglunFromServerBypageFirst)]) {
                [viewController performSelector:@selector(loadPinglunFromServerBypageFirst) withObject:nil];
            }
            [self removeFromSuperview];
        }else{
             [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
       
            
           
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}
//表视图委托
#pragma mark -
#pragma mark table view data source methods

//返回某个表视图有多少行数据
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.quanliList count];
}
//设置行高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return TABLEVIEWCELLHEIGHT;
}


//表视图显示表视图项时调用：第一次显示（根据视图大小显示多少个视图项就调用多少次）以及拖动时调用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
      static NSString *CellIdentifier = @"replyViewCell";
    UITableViewCell *cell =(UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier: CellIdentifier];
    }
    NSDictionary *dict = [self.quanliList objectAtIndex:indexPath.row];
    cell.textLabel.text=[dict objectForKey:@"str2"];
    return cell;
}

//数据源委托
#pragma mark -
#pragma mark table delegate methods


//某行已经被选中时调用
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     NSDictionary *dict = [self.quanliList objectAtIndex:indexPath.row];
    UILabel *yaoqingButtonLabel=(UILabel*)[self viewWithTag:YAOQINGBUTTONLabelTAG];
    yaoqingButtonLabel.text=[dict objectForKey:@"str2"];
    self.selectQuanziId=[dict objectForKey:@"str1"];
    self.mytableView.hidden=YES;
}





-(UITextField*) customTextField:(CGRect) frame{
    
    UITextField *textFied = [[UITextField alloc] initWithFrame:frame];
    textFied.keyboardType=UIKeyboardAppearanceDefault;
    textFied.autocorrectionType = UITextAutocorrectionTypeNo;
    textFied.returnKeyType=UIReturnKeyNext;
    textFied.clearButtonMode=UITextFieldViewModeWhileEditing;
    textFied.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    textFied.backgroundColor=[UIColor  clearColor];
    textFied.borderStyle=UITextBorderStyleNone;
    textFied.textColor=[UIColor blackColor];
    textFied.font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
    textFied.autocorrectionType=UITextAutocorrectionTypeNo;
    [textFied setBorderStyle:UITextBorderStyleNone];
    textFied.returnKeyType = UIReturnKeyDone;
    textFied.keyboardType=UIKeyboardTypeDefault;
    return textFied;
}


- (void)requestFailed:(id)context error:(NSString *)error{
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}


@end
